<template>
  <div>
    <span>全选:</span>
    <input type="checkbox" v-model="allset" />
    <button @click="fn">反选</button>
    <ul>
      <li v-for="item in data" :key="item.num">
        <input type="checkbox" v-model="item.is" />
        <span>{{ item.num }}</span>
      </li>
    </ul>
    <p>你选中的元素，累加的值的和为:{{ num }}</p>
    <button @click="sum">计算</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      flag: false,
      data: [
        { num: 9, is: false },
        { num: 15, is: false },
        { num: 20, is: false },
        { num: 8, is: false },
        { num: 30, is: false },
        { num: 40, is: false },
      ],
      data2: [],
      data3: [],
      num: 0,
    }
  },
  methods: {
    fn() {
      this.data.forEach((item) => (item.is = !item.is))
    },
    sum() {
      this.data2 = []
      this.data.map((item) => {
        item.is === true ? this.data2.push(item.num) : 0
      })
      this.num = this.data2.reduce((q, v) => {
        return q + v
      }, 0)
    },
  },
  computed: {
    allset: {
      get() {
        return this.data.every((item) => item.is)
      },
      set(va) {
        this.data.forEach((item) => (item.is = va))
      },
    },
  },
}
</script>

<style scoped></style>
